import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_smart_heating/common/http.dart';
import 'package:flutter_smart_heating/pages/information/estate/view/map.dart';
import 'package:flutter_smart_heating/pages/information/station/view/map.dart';
import 'package:flutter_smart_heating/ui/src/bmap.dart';
import 'package:flutter_smart_heating/ui/ui.dart';

class InformationPage extends StatefulWidget {
  const InformationPage({super.key});

  @override
  State<InformationPage> createState() => _InformationPageState();
}

class _InformationPageState extends State<InformationPage>
    with SingleTickerProviderStateMixin {
  late TabController tabController;

  late BMFMapController mapController;
  ValueNotifier tabIndex = ValueNotifier<int>(0);
  ValueNotifier isReady = ValueNotifier<bool>(false);

  @override
  void initState() {
    tabController = TabController(length: 3, vsync: this);
    super.initState();
  }

  getCenterPoint(path) {
    var x = 0.0;
    var y = 0.0;
    for (var i = 0; i < path.length; i++) {
      x = x + path[i]['longitude'];
      y = y + path[i]['latitude'];
    }
    x = x / path.length;
    y = y / path.length;
    return BMFCoordinate(y, x);
  }

  fetchCompany() async {
    var res = await Http.instance.post('/api/basic/company/location');

    if (res.code == 1) {
      mapController.setCenterCoordinate(
        getCenterPoint(res.data['data']),
        false,
      );
      List<BMFMarker> markers = [];
      for (var item in res.data['data']) {
        double latitude = item['latitude'];
        double longitude = item['longitude'];

        // /// text经纬度信息
        BMFCoordinate position = BMFCoordinate(latitude, longitude);

        BMFMarker marker = BMFMarker.icon(
          position: position,
          customMap: item,
          centerOffset: Platform.isIOS ? BMFPoint(0, 0.6) : BMFPoint(0, 45),
          identifier: '${item['id']}',
          icon: 'res/images/marker-overly.png',
          canShowCallout: false,
        );
        markers.add(marker);

        Map<String, Color> colors = {
          'primary': UiTheme.primary,
          'online': Colors.green,
          'offline': Colors.red,
          'abnormal': Colors.orange,
        };

        /// 构造text
        BMFText bmfText = BMFText(
          text: ' ${item['icon'] ?? '◉'} ${item['label']} ',
          paragraphSpacing: 10,
          position: position,
          bgColor: colors[item['status']] ?? UiTheme.primary,
          fontColor: Colors.white,
          fontSize: Platform.isIOS ? 15 : 30,
          alignment: BMFTextAlignment.center,
          typeFace: BMFTypeFace(
            textStype: BMFTextStyle.BOLD,
          ),
          zIndex: 0,
          lineSpacing: 10,
          rotate: 0,
        );

        /// 添加text
        mapController.addText(bmfText);
      }
      mapController.addMarkers(markers);

      Map<String, BMFParticleEffectType> effects = {
        "Fireworks": BMFParticleEffectType.Fireworks,
        "Flower": BMFParticleEffectType.Flower,
        "PUnknow": BMFParticleEffectType.PUnknow,
        "RainStorm": BMFParticleEffectType.RainStorm,
        "SandStorm": BMFParticleEffectType.SandStorm,
        "Smog": BMFParticleEffectType.Smog,
        "Snow": BMFParticleEffectType.Snow
      };
      if (effects[res.data['effect']] != null && Platform.isIOS) {
        mapController.showParticleEffect(effects[res.data['effect']]!);
      }
    }
  }

  Map<dynamic, dynamic>? currentCompany;
  ValueNotifier showStation = ValueNotifier<bool>(false);
  ValueNotifier hideMap = ValueNotifier<bool>(false);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: UiPanel(
          width: 300,
          borderRadius: BorderRadius.circular(30),
          height: 35,
          child: TabBar(
            controller: tabController,
            isScrollable: false,
            dividerColor: Colors.transparent,
            splashBorderRadius: BorderRadius.circular(30),
            indicatorSize: TabBarIndicatorSize.tab,
            indicator: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(30),
              gradient: const LinearGradient(
                colors: [
                  Color.fromARGB(255, 11, 232, 248),
                  Color.fromARGB(255, 33, 51, 243),
                ],
              ),
            ),
            indicatorColor: Colors.black,
            labelColor: Colors.white,
            unselectedLabelColor:
                UiTheme(context).matchColor(Colors.black, Colors.white),
            unselectedLabelStyle: const TextStyle(
              fontWeight: FontWeight.normal,
            ),
            labelStyle: TextStyle(
              fontWeight: FontWeight.bold,
              fontSize: UiTheme.fontSize.tabbarFontSize,
              color: Colors.red,
            ),
            tabs: const [
              Tab(text: "热站数据"),
              Tab(text: "热网数据"),
              Tab(text: "小区数据"),
            ],
            onTap: (index) async {
              //  await 0.3.delay();
              // showStation = false;
              // hideMap = false;
              tabIndex.value = index;
            },
          ),
        ),
      ),
      body: Container(
        clipBehavior: Clip.hardEdge,
        decoration: BoxDecoration(
          color: UiTheme(context).matchColor(
              Colors.grey.withOpacity(0.2), Colors.white.withOpacity(0.7)),
          borderRadius: BorderRadius.circular(UiTheme.boxRadiusX),
        ),
        margin: const EdgeInsets.only(top: UiTheme.toolbarSpacing),
        child: Stack(
          children: [
            Positioned.fill(
              child: ValueListenableBuilder(
                valueListenable: hideMap,
                builder: (context, state, widget) {
                  return Offstage(
                    offstage: state,
                    child: SizedBox(
                      width: double.infinity,
                      height: double.infinity,
                      child: BmapWidget(
                        onBMFMapCreated: (controller) {
                          isReady.value = true;
                          mapController = controller;
                          fetchCompany();

                          /// 地图marker点击回调
                          mapController.setMapClickedMarkerCallback(
                              callback: (BMFMarker marker) {
                            currentCompany = marker.customMap;

                            showStation.value = true;
                          });
                        },
                        mapOptions: BMFMapOptions(
                          center:
                              BMFCoordinate(41.741405053796, 123.21987043266),
                          overlookEnabled: false,
                          rotateEnabled: false,
                          zoomLevel: 13,
                          mapPadding: BMFEdgeInsets(
                            left: 30,
                            top: 0,
                            right: 30,
                            bottom: 0,
                          ),
                        ),
                      ),
                    ),
                  );
                },
              ),
            ),
            ValueListenableBuilder(
              valueListenable: isReady,
              builder: (context, state, widget) {
                return state
                    ? Container()
                    : const Align(child: CupertinoActivityIndicator());
              },
            ),
            ValueListenableBuilder(
              valueListenable: showStation,
              builder: (context, state, widget) {
                return state ? sendMapView() : Container();
              },
            ),
            ValueListenableBuilder(
              valueListenable: showStation,
              builder: (context, state, widget) {
                return state ? backButtonView(context) : Container();
              },
            )
          ],
        ),
      ),
    );
  }

  Widget sendMapView() {
    return Positioned.fill(
      child: ValueListenableBuilder(
        valueListenable: tabIndex,
        builder: (context, state, widget) {
          Widget view = Container();
          if (state == 0 || state == 1) {
            view = StationMapView(
              key: ValueKey('station${state == 0 ? '' : '.pipe'}'),
              companyId: currentCompany?['id'],
              showPipeLine: state == 1,
              companyName: currentCompany?['label'],
              onReady: () {
                if (showStation.value) {
                  hideMap.value = true;
                }
              },
            );
          } else if (state == 2) {
            view = EstateMapView(
              companyId: currentCompany?['id'],
              companyName: currentCompany?['label'],
              onReady: () {
                if (showStation.value) {
                  hideMap.value = true;
                }
              },
            );
          }
          return view;
        },
      ),
    );
  }

  Positioned backButtonView(BuildContext context) {
    return Positioned(
      left: 15,
      top: 15,
      child: UiTap(
        onTap: () {
          showStation.value = false;
          hideMap.value = false;
        },
        child: Container(
          padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 4),
          decoration: BoxDecoration(
            color: Theme.of(context).scaffoldBackgroundColor.withOpacity(0.8),
            borderRadius: BorderRadius.circular(30),
            boxShadow: [
              BoxShadow(
                color: Colors.black.withOpacity(0.1),
                spreadRadius: 0,
                blurRadius: 5,
              ),
            ],
          ),
          child: Row(children: [
            const Icon(Icons.arrow_back),
            const SizedBox(width: 5),
            Text(
              currentCompany?['label'] ?? '',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
              ),
            ),
            const SizedBox(width: 5),
          ]),
        ),
      ),
    );
  }
}
